package com.jeeplus.core.qr;

import com.alibaba.fastjson.JSON;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.FileUtils;
import com.jeeplus.modules.monitor.utils.utils.CommonUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import static com.jeeplus.modules.monitor.utils.Achieve.saveToImgByInputStream;

/**
 * @author liangbing
 * @version 1.0
 * @date 2021/3/31 8:59
 * @description 微信小程序二维码生成器
 */
public class MiniappQrTool {

    private static Logger log = LoggerFactory.getLogger(MiniappQrTool.class);

    private static final String Unlimit_MiniCodeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";
    private static final String Limit_MiniQrcodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";

    /**
     * 生成小程序码（菊花码）
     * @param appid 应用ID
     * @param appsecret 应用密钥
     * @param scene 场景（参数），最大32个字符
     * @param page 已经发布的小程序页面，例如 “pages/index/index” ,如果不填写这个字段，默认跳主页面
     * @param width 二维码的宽度
     * @param folderPath 生成图片的保存目录
     * @param filename 生成的图片名称
     * @return
     */
    public static AjaxJson createMiniProgramCode(String appid, String appsecret, String scene, String page, int width, String folderPath, String filename) {
        AjaxJson j = new AjaxJson();

        // 生成调用参数
        String token = CommonUtil.getToken(appid, appsecret).getAccessToken();
        Map<String, Object> params = new HashMap<>();
        params.put("scene", scene);     //参数
        params.put("page", page);       //位置
        params.put("width", width);     //宽度

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(Unlimit_MiniCodeUrl + token);  // 接口
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);           //必须是json模式的 post

        try {
            StringEntity entity;
            entity = new StringEntity(body);

            entity.setContentType("image/png");

            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            //String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + roomFlag + "/paiqrcode/";
            FileUtils.createDirectory(folderPath);
            //String name = "room"+roomNumber+".png";
            saveToImgByInputStream(inputStream, folderPath, filename);  //保存图片

            //j.put("filePath", request.getContextPath()+Global.USERFILES_BASE_URL + roomFlag+"/paiqrcode/"+"room"+roomNumber+".png");
            //j.put("roomFlag",roomFlag);
            //j.put("roomNumber",roomNumber);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("生成小程序二维码失败：" + e.getMessage());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("生成小程序二维码失败：" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("生成小程序二维码失败：" + e.getMessage());
        }

        return j;
    }

    /**
     * 生成小程序二维码 最多10万个
     * @param appid 应用ID
     * @param appsecret 应用密钥
     * @param scene 场景（参数），最大32个字符
     * @param page 已经发布的小程序页面，例如 “pages/index/index” ,如果不填写这个字段，默认跳主页面
     * @param width 二维码的宽度
     * @param folderPath 生成图片的保存目录
     * @param filename 生成的图片名称
     * @return
     */
    public static AjaxJson createMiniProgramQrCode(String appid, String appsecret, String scene, String page, int width, String folderPath, String filename) {
        AjaxJson j = new AjaxJson();

        // 生成调用参数
        String token = CommonUtil.getToken(appid, appsecret).getAccessToken();
        Map<String, Object> params = new HashMap<>();

        String path = page + "?scene=" + scene;

        params.put("path", path);       //扫码进入的小程序页面路径
        params.put("width", width);     //宽度

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(Limit_MiniQrcodeUrl + token);  // 接口
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);           //必须是json模式的 post

        try {
            StringEntity entity;
            entity = new StringEntity(body);

            entity.setContentType("image/png");

            httpPost.setEntity(entity);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            //String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + roomFlag + "/paiqrcode/";
            FileUtils.createDirectory(folderPath);
            //String name = "room"+roomNumber+".png";
            saveToImgByInputStream(inputStream, folderPath, filename);  //保存图片

            //j.put("filePath", request.getContextPath()+Global.USERFILES_BASE_URL + roomFlag+"/paiqrcode/"+"room"+roomNumber+".png");
            //j.put("roomFlag",roomFlag);
            //j.put("roomNumber",roomNumber);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("生成小程序二维码失败：" + e.getMessage());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("生成小程序二维码失败：" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("生成小程序二维码失败：" + e.getMessage());
        }

        return j;
    }
}
